package xyz.xiezc.spider.statistic;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.setting.Setting;
import lombok.extern.slf4j.Slf4j;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.ioc.annotation.Inject;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wb-xzc291800
 * @date 2019/04/15 19:16
 */
@Slf4j
@Component
public class Authenticator {

    @Inject
    Setting setting;

    Map<String, String> userMap = new ConcurrentHashMap<>();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
    DateTimeFormatter expiresFormatter = DateTimeFormatter
            .ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);

    public boolean checklogin(String name, String pwd) {
        String format = LocalDateTime.now().format(dateTimeFormatter);
        StringBuilder stringBuilder = new StringBuilder(format);
        stringBuilder.append(name);
        String userPwd = setting.getByGroup(name, "user");
        stringBuilder.append(userPwd);
        String utf8 = DigestUtil.md5Hex(stringBuilder.toString(), "utf8");
        log.info("正确密码: {}",utf8);
        if (Objects.equals(pwd, utf8)) {
            String uuid = IdUtil.fastSimpleUUID();
            userMap.put(name, uuid);
            return true;
        } else {
            log.warn("name:{} 登录密码不对", name);
            return false;
        }
    }

    public String getUuid(String name) {
        return userMap.get(name);
    }

    public String createCookie(String name) {
        String uuid = userMap.get(name);
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(1);
        String format = localDateTime.format(expiresFormatter);
        StringBuilder cookieStr = new StringBuilder();
        String token = "{'name':'" + name + "','uuid':'" + uuid + "'}";
        cookieStr.append("token=")
                .append(Base64.encode(token))
                .append("; expires=")
                .append(format)
                .append("; path=/");
        return cookieStr.toString();
    }


}
